  
package com.xebest.web.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.RefundReqDto;
import com.xebest.api.service.RefundApiService;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.util.MD5Util;
import com.xebest.common.util.UUIDUtil;
import com.xebest.config.XeVenEpayConfig;
import com.xebest.constant.XeErrorCode;
import com.xebest.util.HttpTookit;
import com.xebest.web.service.XeVenEpayService;

/**
 * 易支付业务操作接口实现
 * @desc: xebest-erp  
 * @author: 李贝贝  
 * @createTime: 2017年7月3日 上午10:06:54  
 * @history:  
 * @version: v1.0
 */
@Service
public class XeVenEpayServiceImpl implements XeVenEpayService {
	 private static final Logger log = LoggerFactory.getLogger(XeVenEpayServiceImpl.class);//日志记录类
	 
	 @Autowired
	 private XeVenEpayConfig xeVenEpayConfig;//易支付参数信息 
	 
	 @Autowired
	 private RefundApiService refundApiService ;//支付中心 退款服务 v3.1.3 add 
	 
	 /**
	  * 货到付款易支付创建POS刷卡订单
	  * @author: 李贝贝
	  * @createTime: 2017年6月29日 下午5:53:00  
	  * @history:  
	  * @param orderId 订单号
	  * @param userPayAmout void 易支付创单用户需要支付金额 
	  */
	 public String insertPostOrder(String orderId,String userPayAmout,String epayAccount) throws Exception{
		 log.info("货到付款易支付创建POS刷卡订单,单号{},金额{}",orderId,userPayAmout);
		 log.info("获取易支付参数信息{}",xeVenEpayConfig.toString());
		/* Map<String,String> paramEpay = new HashMap<String,String>();
		 paramEpay.put("orderName", "鲜易云ERP订单");
		 paramEpay.put("merOrderId", orderId);  //商户订单 餐饮订单
		 paramEpay.put("merId", xeVenEpayConfig.getMerId());//商户号
		
	   	 paramEpay.put("orderAmount", userPayAmout); //支付金额
		 paramEpay.put("sellerLoginName",xeVenEpayConfig.getPayZiyingAccount());//卖家易支付账户
		 //查询易支付账户
		 paramEpay.put("buyerLoginName",epayAccount);//TODO 设置买家易支付账户
		 
		 paramEpay.put("notifyUrl", xeVenEpayConfig.getPayNotifyUrl());
		 paramEpay.put("nonceStr", UUIDUtil.getUUID32Str());	//加密随机数
		 paramEpay.put("sign", this.getSignString(paramEpay,xeVenEpayConfig.getMerKey()) );	//加密验证串
		 String resultStr = HttpTookit.doPost(xeVenEpayConfig.getMerchantApi()+"/posOrder/create.shtml", paramEpay);	
		 log.info("insertPostOrder 返回结果：{}",resultStr);
		 return resultStr;*/
		 return null;
	 }
	 /**
	  * 接入TMS订单
	  * 货到付款易支付修改POS刷卡订单金额信息
	  * @author: 李贝贝
	  * @createTime: 2017年7月5日 下午2:47:03  
	  * @history:  
	  * @param orderId
	  * @param userPayAmout
	  * @return
	  * @throws Exception String
	  */
	 public  String updatePostOrder(String orderId,String userPayAmout,String epayAccount) throws Exception{
		 log.info("货到付款易支付修改POS刷卡订单,单号{},金额{}",orderId,userPayAmout);
		 log.info("获取易支付参数信息{}",xeVenEpayConfig.toString());
		 /*Map<String,String> paramEpay = new HashMap<String,String>();
		 paramEpay.put("orderName", "鲜易云ERP订单");
		 paramEpay.put("merOrderId", orderId);  //商户订单 餐饮订单
		 paramEpay.put("merId", xeVenEpayConfig.getMerId());//商户号
		
	   	 paramEpay.put("orderAmount", userPayAmout); //支付金额
		 paramEpay.put("sellerLoginName",xeVenEpayConfig.getPayZiyingAccount());//卖家易支付账户
		 //查询易支付账户
//		 paramEpay.put("buyerLoginName",epayAccount);//TODO 设置买家易支付账户
		 
		 paramEpay.put("notifyUrl", xeVenEpayConfig.getPayNotifyUrl());
		 paramEpay.put("nonceStr", UUIDUtil.getUUID32Str());	//加密随机数
		 paramEpay.put("sign", this.getSignString(paramEpay,xeVenEpayConfig.getMerKey()) );	//加密验证串
		 String resultStr = HttpTookit.doPost(xeVenEpayConfig.getMerchantApi()+"/posOrder/updateOrder.shtml", paramEpay);	
		 log.info("insertPostOrder 返回结果：{}",resultStr);
		 return resultStr;*/
		 return null;
	 }

	/**
	 * 此方法支持支付类型为： 其它支付方式可以调用 调用易支付进行退款操作 除去微信支付的方式
	 * 
	 * @author: 李贝贝
	 * @createTime: 2017年7月4日 下午7:58:23
	 * @history:
	 * @param mOrderId 主订单号
	 * @param epayAccount 买家易支付账号
	 * @param refundNo  退款单号
	 * @param amount  退款金额
	 * @return String
	 */
	public String refundMoney(String mOrderId, String epayAccount, String refundNo, String amount,Integer refundType) throws Exception {
		log.info("其它支付方式调用易支付进行退款操作,单号{},退款单号{},金额{}", mOrderId, refundNo, amount);
		String resultStr = this.createRefundOrder(mOrderId,refundNo,amount,refundType);
		/*Map<String, String> mapEpay = new HashMap<String, String>();
		mapEpay.put("partner", xeVenEpayConfig.getMerId());// 商户号
		mapEpay.put("orderId", mOrderId);
		mapEpay.put("subOrderId", refundNo);
		mapEpay.put("buyer", epayAccount);
		mapEpay.put("amount", amount);
		mapEpay.put("splitSeller", xeVenEpayConfig.getPayZiyingAccount());// 供应商易支付账号
		String md5ParamStr = xeVenEpayConfig.getMerId() + mOrderId + epayAccount + amount + xeVenEpayConfig.getMerKey();// 验签字符串：md5(partner+orderId+buyer+amount+merKey)
		mapEpay.put("sign", MD5Util.md5(md5ParamStr));
		String resultStr = HttpTookit.doPost(xeVenEpayConfig.getPayRefundHttpUrl() + "/refund/orderRefund.shtml",
				mapEpay);*/
		return resultStr;
	}

	/**
	 * 支付中心创建退款单
	 * @author: 李贝贝
	 * @createTime: 2018年6月13日 下午2:57:58  
	 * @history:  
	 * @param mOrderId
	 * @param refundNo
	 * @param amount void
	 */
	private String createRefundOrder(String mOrderId,  String refundNo, String amount,Integer refundType){
		RefundReqDto reqDto = new RefundReqDto();
		String resultStr =null;
		reqDto.setOrderId(mOrderId);
		reqDto.setRefundAmount(new BigDecimal(amount));
		reqDto.setRefundCode(refundNo);
		reqDto.setRefundType(refundType);
		reqDto.setCreateUser("xebest");
		log.info("支付中心创建退款单入参{}",JSONObject.toJSONString(reqDto));
		BaseResponseDTO responeDto = refundApiService.createRefund(reqDto);
		log.info("支付中心创建退款单返回参数{}",JSONObject.toJSONString(responeDto));
		if (null != responeDto && responeDto.getStatus().equals(XeErrorCode.PORJECT_SUCCESS)) {
			JSONObject retStr = new JSONObject();
			retStr.put("resultCode", "0000");
			resultStr = retStr.toJSONString();
		}
		return resultStr;
	}
	
	/**
	 * 此方法支持支付类型为：微信支付 调用易支付进行退款操作
	 * @author: 李贝贝
	 * @createTime: 2017年7月4日 下午7:58:23
	 * @history:
	 * @param mOrderId   主订单号
	 * @param refundNo 退款单号
	 * @param amount   退款金额
	 * @return String
	 */
	public String refundMoneyByWebChat(String mOrderId, String refundNo, String amount,Integer refundType) throws Exception {
		log.info("微信支付调用易支付进行退款操作,单号{},退款单号{},金额{}", mOrderId, refundNo, amount);
		/*Map<String, String> mapEpay = new HashMap<String, String>();
		mapEpay.put("merPayOrderId", mOrderId);// 商户支付订单号
		mapEpay.put("merTransferOrderId", refundNo);// 商户结转订单号，商户唯一
		mapEpay.put("merTransferOrderName", "TUIKUANDANG_" + refundNo);
		mapEpay.put("type", "refund");// refund:退款(退款至付款方易支付余额)
		mapEpay.put("amount", amount);// 结算金额，单位:元
		mapEpay.put("merId", xeVenEpayConfig.getMerId());// 商户号
		mapEpay.put("nonceStr", UUIDUtil.getUUID32Str()); // 加密随机数
		mapEpay.put("sign", this.getSignString(mapEpay, xeVenEpayConfig.getMerKey()));
		String resultStr = HttpTookit.doPost(xeVenEpayConfig.getMerchantApi() + "/wxpay/transfer.shtml", mapEpay);
		return resultStr;*/
	    String resultStr = this.createRefundOrder(mOrderId,refundNo,amount,refundType);
		return resultStr;
	}

	/**
	 * 把数组所有元素排序，并按照"参数=参数值"的模式用"&”字符拼接成字符串
	 * 
	 * @author: 李贝贝
	 * @createTime: 2017年7月4日 下午7:51:41
	 * @history:
	 * @param params 需要排序并参与字符拼接的参数组
	 * @param merKey    商户KEY
	 * @return String 拼接后加密字符串
	 */
	private String getSignString(Map<String, String> params, String merKey) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		StringBuffer pre = new StringBuffer();
		String key = null;
		String value = null;
		for (int i = 0; i < keys.size(); i++) {
			key = keys.get(i);
			value = params.get(key);
			if (value == null || "".equals(value.trim()))
				continue;
			pre = pre.append(key).append("=").append(value).append("&");
		}
		pre.append("merKey=" + merKey);
		String preStr = pre.toString();
		log.info("拼装参数为：{}", preStr);
		return MD5Util.md5(preStr);
	}
	  
	/**
	 * 易支付退款进度详情
	 * @author: 李贝贝
	 * @createTime: 2017年7月5日 下午2:29:37
	 * @history:
	 * @param orderId 订单号
	 * @param refundNo 退款单号
	 * @return String
	 */
	public String queryRefundMoneyDetail(String orderId, String refundNo) throws Exception {
		log.info("易支付退款进度详情,单号{},退款单号{}",orderId,refundNo);
		Map<String,String> map = new HashMap<String,String>();
		String nonceStr = UUIDUtil.getUUID32Str();
		String ngs = xeVenEpayConfig.getMerId() + orderId + refundNo + nonceStr + xeVenEpayConfig.getMerKey();
		map.put("merId",xeVenEpayConfig.getMerId());
		map.put("merOrderId",orderId);
		map.put("merRefundId",refundNo);
		map.put("nonceStr",nonceStr);
		map.put("sign",MD5Util.md5(ngs));
		String resultStr = HttpTookit.doPost(xeVenEpayConfig.getPayRefundHttpUrl() + "/order/queryRefundOrder.shtml",map);
		return resultStr ;
	}

	/**
	 * @Author:chenjing
	 * @Description: 在线支付手动同步状态
	 * @Date:20:47 2017/9/6
	 * @params: * @param null
	 * @return:
	 */
	@Override
	public String queryRefundMoneyOnlineDetail(String orderId) throws Exception {
		log.info("易支付退款进度详情,单号{}",orderId);
		Map<String,String> map = new HashMap<String,String>();
		String ngs = xeVenEpayConfig.getMerId() + orderId  + xeVenEpayConfig.getMerKey();
		map.put("partner",xeVenEpayConfig.getMerId());
		map.put("dealOrder",orderId);
		map.put("sign",MD5Util.md5(ngs));
		String resultStr = HttpTookit.doPost(xeVenEpayConfig.getPayRefundHttpUrl() + "/order/queryOrder.shtml",map);
		return resultStr ;
	}

	/**
	 * 此方法支持支付类型为：微信支付 退款进度详情
	 * @author: 李贝贝
	 * @createTime: 2017年7月5日 下午2:30:28
	 * @history:
	 * @param refundNo
	 * @return String
	 */
	public String queryRefundMoneyByWebChat(String refundNo)throws Exception {
		log.info("微信支付退款进度详情,退款单号{}",refundNo);
		Map<String,String> map = new HashMap<String,String>();
		map.put("merOrderId",refundNo);//退款单号
		map.put("merId", xeVenEpayConfig.getMerId());//商户号
		map.put("nonceStr", UUIDUtil.getUUID32Str());
		map.put("sign", this.getSignString(map,xeVenEpayConfig.getMerKey()));
		String resultStr = HttpTookit.doPost(xeVenEpayConfig.getMerchantApi() + "/m2a/detail.shtml",map);
		return resultStr;
	}		     

		
	   
}
  
